package kr.hkit.powerjava.chapter24.work3;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

public class StudentDao implements Dao<Student> {

	ArrayList<Student> lists;
	private static final String FILE_NAME = "Student.dat";

	@Override
	public void addItem(Student item) {
		// TODO 목록에 추가
		lists.add(item);
	}

	@Override
	public void deleteItem(int idx) {
		// TODO idx의 내용을 받아서 삭제
		lists.remove(searchIdx(idx));
	}

	@Override
	public void updateItem(int idx, Subject update) {
		// TODO idx의 내용을 받아서 수정
		Student std;
		if ((std = searchIdx(idx)) != null) {
			std.setSub(update);
		} else {
			System.out.println("없음");
		}
	}

	@Override
	public Student searchIdx(int idx) {
		Iterator<Student> iter = lists.iterator();
		while (iter.hasNext()) {
			if (iter.next().getStdNum() == idx)
				return (Student) iter;
		}
		return null;
	}

	@Override
	public void prnItems(Comparator<Student> comp) {
		// TODO 출력
		if (comp == null) {
			Collections.sort(lists);
		} else {
			Collections.sort(lists, comp);
		}

		for (Student std : lists) {
			System.out.println(std);
		}
	}

	@Override
	public void loadData() {
		// TODO 파일 읽어오기
		ObjectInputStream ois = null;

		try {// 파일 불러오기
			ois = new ObjectInputStream(new BufferedInputStream(
					new FileInputStream(StudentDao.FILE_NAME)));
			lists = (ArrayList<Student>) ois.readObject();
		} catch (FileNotFoundException e) {// 처음 실행시켰을 경우(파일이 생성되지 않은 상태)
			try {
				new File(StudentDao.FILE_NAME).createNewFile();
				lists = new ArrayList<>();
			} catch (Exception e1) {
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch (Exception e) {
				}
			}
		}
	}

	@Override
	public void saveData() {
		// TODO 여태 작업한 내용 파일에 저장
		ObjectOutputStream oos = null;

		try {
			oos = new ObjectOutputStream(new BufferedOutputStream(
					new FileOutputStream(StudentDao.FILE_NAME)));
			oos.writeObject(lists);
			oos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (oos != null) {
				try {
					oos.close();
				} catch (Exception e) {
				}
			}
		}
	}

}
